//加载express
const express = require('express');
//声明路由
const router = express.Router();
//导入数据模型
const {
  order
} = require('../model/db')
//===============API写下面================================================
// 保存订单
router.post('/addOrder', async (req, res) => {
  try {
    await order.create(req.body);
    res.send('success');
  } catch (error) {
    res.send('fail');
    console.log(error)
  }
})

//小程序 获取订单数量
router.get('/orderCount', async (req, res) => {
  const {
    openid,
    acceptMan,
    status
  } = req.query;
  let data = {}; //为空，则获取所有订单
  if (openid) { //获取我的订单
    data = {
      openid
    };
  } else if (acceptMan) { //获取我帮助的订单
    data = {
      acceptMan
    };
  } else if (status) { //获取状态为待帮助的订单
    data = {
      status
    };
  }
  const count = await order.countDocuments(data)
  console.log(count)
  res.send({
    count
  })
})
//小程序 获取订单
router.get('/orderList', async (req, res) => {
  const {
    page,
    pageSizes,
    openid,
    acceptMan,
    status
  } = req.query;
  let data = {}; //为空，则获取所有订单
  if (openid) { //获取我的订单
    data = {
      openid
    };
  } else if (acceptMan) { //获取我帮助的订单
    data = {
      acceptMan
    };
  } else if (status) { //获取状态为待帮助的订单
    data = {
      status
    };
  }
  try {
    const result = await order.find(data).skip(page).limit(pageSizes).sort({
      publicTime: -1
    });
    res.send(result)
  } catch (err) {
    console.log(err)
    res.send('fail');
  }
})

//统计我完成的订单数量和金额
router.get('/helpedOrders', async (req, res) => {
  try {
    const {
      acceptMan,
      status
    } = req.query;
    const total = await order.aggregate([{
        $match: {
          acceptMan,
          status
        }
      },
      {
        $group: {
          _id: '$acceptMan', //按照acceptMan分组
          orderCounts: {
            $sum: 1
          },
          earnMoney: {
            $sum: '$payMoney'
          }
        }
      }
    ]);
    res.send({
      status: 'success',
      total
    })
  } catch (error) {
    console.log(error)
    res.send({
      status: 'fail'
    })
  }
})

//小程序 删除我的订单
router.get('/delOrder', async (req, res) => {
  try {
    const {
      id
    } = req.query;
    await order.findByIdAndDelete(id)
    res.send('success')
  } catch (error) {
    console.log(error)
    res.send('fail')
  }
})

//接单、确认订单
router.post('/updateOrder', async (req, res) => {
  try {
    const {
      id,
      status,
      acceptMan,
      acceptTime,
      confirmTime
    } = req.body;
    let data = {}
    if (acceptTime) { //接单
      data = {
        acceptMan,
        acceptTime,
        status
      }
    } else if (confirmTime) { //确认订单
      data = {
        confirmTime,
        status
      }
    } else if (status) {
      data = {
        status
      }
    }
    await order.findByIdAndUpdate(id, data)
    res.send('success')
  } catch (err) {
    res.send('fail');
    console.log(err);
  }

})
//获取订单详情
router.get('/orderDetail', async (req, res) => {
  try {
    const mongoose = require('mongoose');
    const result = await order.aggregate([{
        $lookup: {
          from: 'userInfo',
          localField: 'acceptMan',
          foreignField: 'openid',
          as: 'acceptManInfo'
        }
      },
      {
        $match: {
          _id: mongoose.Types.ObjectId(req.query.id)
        }
      }
    ])
    res.send({
      status: 'success',
      result
    });
  } catch (error) {
    console.log(error)
    res.send({
      status: 'fail'
    })
  }

})

//管理后台 获取所有订单
router.get('/admGetOrders', async (req, res) => {
  try {
    const {
      currentPage: page,
      pagesize
    } = req.query
    //获取数据库中的记录总数
    const total = await order.countDocuments()
    //分页获取管理员
    const result = await order.find().skip((page - 1) *
      pagesize).limit(pagesize).sort({
      time: -1
    })
    console.log(result)
    res.send({
      status: 'success',
      total,
      result
    })
  } catch (error) {
    console.log(error)
    res.send({
      status: 'fail'
    })
  }
})

//管理后台 数据可视化 统计
router.get('/orderTotal', async (req, res) => {
  try {
    const result = await order.aggregate([{
      $group: {
        _id: '$orderType',
        orderCounts: {
          $sum: 1
        }
      }
    }])
    res.send({
      status: 'success',
      result
    })
  } catch (error) {
    console.log(error)
    res.send({
      status: 'fail'
    })
  }
})
//===============API写在上面=============================================
//导出路由
module.exports = router